<template>
	<view class="container">
		<view v-if="loading" class="loading">
			<text>加载中...</text>
		</view>
		
		<view v-else-if="device" class="content">
			<!-- 设备基本信息 -->
			<view class="section">
				<view class="section-title">基本信息</view>
				<view class="info-card">
					<view class="info-row">
						<text class="label">设备名称</text>
						<text class="value">{{ device.deviceName }}</text>
					</view>
					<view class="info-row">
						<text class="label">设备编号</text>
						<text class="value">{{ device.deviceCode }}</text>
					</view>
					<view class="info-row">
						<text class="label">设备类型</text>
						<text class="value">{{ device.deviceType }}</text>
					</view>
					<view class="info-row">
						<text class="label">制造商</text>
						<text class="value">{{ device.manufacturer || '—' }}</text>
					</view>
					<view class="info-row">
						<text class="label">安装位置</text>
						<text class="value">{{ device.installLocation || '—' }}</text>
					</view>
					<view class="info-row">
						<text class="label">设备状态</text>
						<text class="value status" :style="{ color: getStatusColor(device.status) }">
							{{ getStatusText(device.status) }}
						</text>
					</view>
				</view>
			</view>

			<!-- 位置信息 -->
			<view class="section" v-if="device.longitude && device.latitude">
				<view class="section-title">位置信息</view>
				<view class="info-card">
					<view class="info-row">
						<text class="label">经度</text>
						<text class="value">{{ device.longitude }}</text>
					</view>
					<view class="info-row">
						<text class="label">纬度</text>
						<text class="value">{{ device.latitude }}</text>
					</view>
				</view>
			</view>

			<!-- 负责人信息 -->
			<view class="section">
				<view class="section-title">负责人信息</view>
				<view class="info-card">
					<view class="info-row">
						<text class="label">负责人</text>
						<text class="value">{{ device.responsiblePerson || '—' }}</text>
					</view>
					<view class="info-row">
						<text class="label">联系电话</text>
						<text class="value">{{ device.contactPhone || '—' }}</text>
					</view>
					<view class="info-row">
						<text class="label">安装时间</text>
						<text class="value">{{ formatDate(device.installTime) }}</text>
					</view>
				</view>
			</view>

			<!-- 在线状态 -->
			<view class="section">
				<view class="section-title">在线状态</view>
				<view class="info-card">
					<view class="info-row">
						<text class="label">当前状态</text>
						<text class="value status" :style="{ color: getStatusColor(device.status) }">
							{{ getStatusText(device.status) }}
						</text>
					</view>
					<view class="info-row">
						<text class="label">最后更新</text>
						<text class="value">{{ formatDate(device.updateTime) }}</text>
					</view>
				</view>
			</view>
		</view>

		<view v-else class="empty">
			<text>设备信息不存在</text>
		</view>

		<!-- 操作按钮 -->
		<view class="actions" v-if="device">
			<button class="btn-primary" @click="editDevice">编辑设备</button>
			<button class="btn-secondary" @click="viewConfig">查看配置</button>
			<button class="btn-danger" @click="handleDeleteDevice">删除设备</button>
		</view>
		
		<!-- 调试按钮 -->
		<view class="debug-actions" v-if="!device">
			<button class="btn-debug" @click="goDebug">调试页面</button>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { useDeviceStore } from '@/stores/device.js'
import { getDeviceDetail, deleteDevice as deleteDeviceApi } from '@/api/device.js'

const deviceStore = useDeviceStore()
const loading = ref(false)
const device = ref(null)

const getStatusColor = (status) => {
	const colorMap = {
		1: '#4cd964', // 在线 - 绿色
		2: '#999999', // 离线 - 灰色
		3: '#dd524d'  // 故障 - 红色
	}
	return colorMap[status] || '#999999'
}

const getStatusText = (status) => {
	const textMap = {
		1: '在线',
		2: '离线',
		3: '故障'
	}
	return textMap[status] || '未知'
}

const formatDate = (date) => {
	if (!date) return '—'
	return new Date(date).toLocaleString('zh-CN')
}

// 获取设备详情
const fetchDetail = async () => {
	try {
		loading.value = true
		const deviceId = getCurrentDeviceId()
		
		if (!deviceId) {
			uni.showModal({
				title: '参数错误',
				content: '未获取到设备ID，请从设备列表重新进入',
				showCancel: false,
				success: () => {
					uni.navigateBack()
				}
			})
			return
		}
		
		console.log('开始获取设备详情，设备ID:', deviceId)
		const res = await getDeviceDetail(deviceId)
		console.log('设备详情响应:', res)
		
		if (res && res.code === 200) {
			device.value = res.obj
			deviceStore.setCurrentDevice(res.obj)
			console.log('设备详情加载成功:', device.value)
		} else {
			uni.showModal({
				title: '获取失败',
				content: res?.msg || '获取设备详情失败',
				showCancel: false
			})
		}
	} catch (error) {
		console.error('获取设备详情失败:', error)
		
		let errorMessage = '网络错误，请重试'
		if (error.statusCode === 404) {
			errorMessage = '设备不存在'
		} else if (error.statusCode === 500) {
			errorMessage = '服务器错误'
		}
		
		uni.showModal({
			title: '获取失败',
			content: errorMessage + '\n\n错误详情：' + JSON.stringify(error),
			showCancel: false
		})
	} finally {
		loading.value = false
	}
}

// 获取当前设备ID
const getCurrentDeviceId = () => {
	// 从页面参数获取
	const pages = getCurrentPages()
	const currentPage = pages[pages.length - 1]
	const deviceId = currentPage.options?.deviceId
	
	console.log('页面参数:', currentPage.options)
	console.log('设备ID:', deviceId)
	
	return deviceId
}

// 编辑设备
const editDevice = () => {
	uni.navigateTo({
		url: `/pages/device/form?deviceId=${device.value.deviceId}&mode=edit`
	})
}

// 查看配置
const viewConfig = () => {
	uni.navigateTo({
		url: `/pages/device/config?deviceId=${device.value.deviceId}`
	})
}

// 删除设备
const handleDeleteDevice = () => {
	uni.showModal({
		title: '确认删除',
		content: '确定要删除此设备吗？删除后无法恢复。',
		success: async (res) => {
			if (res.confirm) {
				try {
					uni.showLoading({ title: '删除中...' })
					const result = await deleteDeviceApi(device.value.deviceId)
					if (result && result.code === 200) {
						uni.showToast({ title: '删除成功', icon: 'success' })
						setTimeout(() => {
							uni.navigateBack()
						}, 1500)
					} else {
						uni.showToast({
							title: result?.msg || '删除失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('删除设备失败:', error)
					uni.showToast({
						title: '删除失败，请重试',
						icon: 'none'
					})
				} finally {
					uni.hideLoading()
				}
			}
		}
	})
}

// 跳转调试页面
const goDebug = () => {
	uni.navigateTo({
		url: '/pages/device/debug'
	})
}


// 页面显示时刷新数据
onShow(() => {
	console.log('页面显示，检查是否需要刷新设备详情')
	
	// 检查是否有设备更新标志
	const deviceUpdated = uni.getStorageSync('device_updated')
	if (deviceUpdated) {
		console.log('检测到设备已更新，刷新详情')
		// 清除更新标志
		uni.removeStorageSync('device_updated')
		// 刷新设备详情
		fetchDetail()
	} else {
		console.log('设备未更新，使用缓存数据')
	}
})

onMounted(() => {
	fetchDetail()
})
</script>

<style lang="scss" scoped>
.container {
	padding: 20rpx;
	background: #f8fffe;
	min-height: 100vh;
}

.loading, .empty {
	text-align: center;
	padding: 80rpx 0;
	color: #999;
}


.section {
	margin-bottom: 30rpx;
}

.section-title {
	font-size: 28rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 20rpx;
	padding-left: 10rpx;
	border-left: 6rpx solid #2E7D32;
}

.info-card {
	background: #ffffff;
	border: 2rpx solid #e8f5e8;
	border-radius: 16rpx;
	padding: 30rpx;
	box-shadow: 0 4rpx 20rpx rgba(46, 125, 50, 0.1);
}

.info-row {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #f0f0f0;
	
	&:last-child {
		border-bottom: none;
	}
}

.label {
	font-size: 26rpx;
	color: #666;
	font-weight: 500;
}

.value {
	font-size: 26rpx;
	color: #333;
	
	&.status {
		font-weight: bold;
	}
}

.actions {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background: #ffffff;
	padding: 20rpx;
	border-top: 1rpx solid #e8f5e8;
	display: flex;
	gap: 20rpx;
}

.btn-primary, .btn-secondary, .btn-danger {
	flex: 1;
	height: 80rpx;
	border-radius: 10rpx;
	font-size: 26rpx;
	border: none;
}

.btn-primary {
	background-color: #2E7D32;
	color: #ffffff;
}

.btn-secondary {
	background-color: #f8f9fa;
	color: #333;
	border: 1rpx solid #ddd;
}

.btn-danger {
	background-color: #dd524d;
	color: #ffffff;
}

.debug-actions {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background: #ffffff;
	padding: 20rpx;
	border-top: 1rpx solid #e8f5e8;
}

.btn-debug {
	width: 100%;
	height: 80rpx;
	background-color: #ff9800;
	color: #ffffff;
	border: none;
	border-radius: 10rpx;
	font-size: 26rpx;
}
</style>
